//@ sourceURL=add.js

//添加窗口弹出
function createEditWindow(id, label, formId, options){
	options = $.extend({
        width: 400,
        height: 300
    },options || {});
	//初始化添加窗口
    var addWindow = $("#" + id);
    addWindow.dialog({
        autoOpen: false,
        width: options.width,
        height: options.height,
        resizable: false,
        title: label,
        modal: true,
        buttons: {
            "保存": function () {
                $("#" + formId).submit();
            },
            "取消": function () {
                $(this).dialog("close");
            }
        },
        close: function(){
        	$(".jBox-wrapper").remove();
        }
    });
    return addWindow;
}

//添加角色（角色树配置）
var role_setting = {
    check: {
        enable: true,
        chkboxType:  { "Y" : "", "N" : "" },
        chkStyle: "radio"
    },
    view: {
        dblClickExpand: false
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {
        onCheck: roleTreeCheck
    }
};

var zTree,rolezTree;
var addWindow;
var loadDiv = null;
$(function () {
	loadDiv = $("#loadDiv").loading();//初始化提示操作执行中
	$("#updateDialog").empty();
	$("#tabs").tabs();
	initRoleList();
	//初始化添加角色时勾选的权限树
	initRoleAuthorityTree();
 	initAddWindow();
 	var height = getWindowHeight()- $("#tableDiv").height()-$("#tabsUl").height()-$("#btnDiv").height()-50;
	$("#baseAuth").height(height);
	$("#menuAuth").height(height);
});

function initRoleList(){
	$("#roleList").click({menuContentId:"roleListDiv"}, showMenu);
	$.post(getPath() + "base/role/tree",{},function(result){
		if(result.isSuccess){
			var treeNodes = result.resultObject;
			rolezTree = $.fn.zTree.init($("#roleListzTree"),role_setting,treeNodes); 
		}
	},"json");
}

function initRoleAuthorityTree(){
	//获取角色的基本权限树（菜单权限除外）
	post(getPath() + "base/authority/tree",{pid:0},function(treeNodes){
		//表格型权限选择
		var html="";
		var pid=0;
		var childtreeNumber=0;
		html+="<tr><td style='width:240px'><span class='checkbox' id='"+treeNodes[1].id+"' pid='1' name='baseAuthority' onclick='changeBaseAllCheck("+treeNodes[1].id+");'></span><span style='float:left'>"+treeNodes[1].title+"</span></td>";
		pid=treeNodes[1].id;
		for(var nodeNumber=2;nodeNumber<treeNodes.length;nodeNumber++){
			if(treeNodes[nodeNumber].pId==1){
				childtreeNumber=0;
				html+="</td></tr><tr><td style='width:240px'><span  class='checkbox' id='"+treeNodes[nodeNumber].id+"' pid='1' name='baseAuthority' onclick='changeBaseAllCheck("+treeNodes[nodeNumber].id+");'></span><span style='float:left'>"+treeNodes[nodeNumber].title+"</span></td>";
				pid=treeNodes[nodeNumber].id;
			}else{
				childtreeNumber++;
				if(childtreeNumber==1){
					html+="<td>";
					}
				html+="<div style='float:left'><span class='checkbox' id='"+treeNodes[nodeNumber].id+"' pid='"+pid+"' name='baseAuthority' onclick='changeBaseChildCheck("+pid+","+treeNodes[nodeNumber].id+");'></span><span style='float:left;width:200px;text-align:left;'>"+treeNodes[nodeNumber].title+"</span></div>";
				
			}
			}
			html+="</td></tr>";
			$("#baseAuthority").html(html);
	});
	//获取角色的操作权限树
	post(getPath() + "base/authority/tree/getMenuLookAndOperateAuthorityAsTree",{},function(treeNodes){
		var pid='';
		var html="";
		var div1="";
		var menu_div_clear="";
		var menuAuthority_div="";
		for(var nodeNumber=0;nodeNumber<treeNodes.length;nodeNumber++){
			pid=treeNodes[nodeNumber].pId;
			menu_div_clear="#"+pid;
			$(menu_div_clear).remove();
		}
		for(var nodeNumber=0;nodeNumber<treeNodes.length;nodeNumber++){
			if(treeNodes[nodeNumber].pId=="462"){
				html="<div id='"+treeNodes[nodeNumber].id+"' class='menuAuthority'><div class='oneMenu'><span class='checkbox' style='float:left;' id='"+treeNodes[nodeNumber].id+"' pid='-1' name='menuAuthority' onclick='changeMenuCheck("+treeNodes[nodeNumber].id+");'></span><span class='menuTitle'>"+treeNodes[nodeNumber].title+"</span></div></div>";
				$("div[id=462]").append(html);
			}else{
				pid=treeNodes[nodeNumber].pId;
				menuAuthority_div="#"+pid;
				
				if(treeNodes[nodeNumber].open){
					if($(menuAuthority_div).length <= 0){
						div1="<div id='"+treeNodes[nodeNumber].pId+"'></div>"
						$("#menuAuth").append(div1);
					}
					html="<div id='"+treeNodes[nodeNumber].id+"' class='menuAuthority' style='margin:5px 5px 5px 184px;'><div class='twoMenu'><span  class='checkbox' id='"+treeNodes[nodeNumber].id+"' pid='-1' name='menuAuthority' onclick='changeMenuCheck("+treeNodes[nodeNumber].id+");'></span><span class='menuTitle'>"+treeNodes[nodeNumber].title+"</span></div></div>";
					$("div[id="+treeNodes[nodeNumber].pId+"]").append(html);
				}else{
					if(treeNodes[nodeNumber].id=='allcheck'){
						if($(menuAuthority_div).length <= 0){
							div1="<div id='"+treeNodes[nodeNumber].pId+"'></div>"
							$("#menuAuth").append(div1);
						}
						html="<div pid='"+pid+"' class='menuAuthority' style='margin: 3px 3px 3px 184px;overflow:hidden;padding:3px 0 3px 5px;'><span class='checkbox' id='allcheck' pid='"+pid+"' name='menuAuthority' onclick='changeMenuAllCheck("+pid+");' ></span><span class='operateAuthority'>全选</span></div>";
						$("div[id="+treeNodes[nodeNumber].pId+"]").append(html);
					}else{
						if($(menuAuthority_div).length <= 0){
							div1="<div id='"+treeNodes[nodeNumber].pId+"'></div>"
							$("#menuAuth").append(div1);
						}
						html="<div style='float:left'><span class='checkbox' class='menuAuthority' id='"+treeNodes[nodeNumber].id+"' pid='"+pid+"' name='menuAuthority' onclick='changeMenuChildCheck("+treeNodes[nodeNumber].id+");'></span><span class='operateAuthority'>"+treeNodes[nodeNumber].title+"</span></div>";
						$("div[pid="+treeNodes[nodeNumber].pId+"]").append(html);
					}

				}
			}
		}
		
	});
}

//参考角色树选择的触发事件
function roleTreeCheck(event,treeId,treeNode){
	$("#roleList").val("");
	//取消上一次勾选权限树的信息
	$("span[name=baseAuthority]").removeClass("selected");
	$("span[name=menuAuthority]").removeClass("selected");
	
	var roleId = treeNode.id;
	if(treeNode.checked){
		$("#roleList").val(treeNode.name);
		post(getPath() + "base/roleAuthority/getRoleAuthorityInfoByRoleId",{roleId:roleId},function(result){
			for(var i=0;i<result.length;i++){
				var authorityType = result[i].authorityType;
				var authorityId = result[i].authorityId;
				if(authorityType == 1){
					$("span[name=baseAuthority][id="+authorityId+"]").addClass("selected");
					$("span[name=baseAuthority][pid="+authorityId+"]").addClass("selected");
				}else if(authorityType == 2){
					$("span[name=menuAuthority][id="+authorityId+"]").addClass("selected");
				}else{
					changeMenuChildCheck(authorityId);
				}
			}
		});
	}
	
}

/**
 * 初始化添加窗口
 */
function initAddWindow(){
	//声明消息提示
    var toolTips = new Object();
    //设置表单验证
    var validator = $("#addForm").validate({
        rules:{
        	roleName:"required",
        	//jQuery远程后台判断角色标识是否唯一
        	roleFlag:{
        		required:true,
        		remote:{
        			url: getPath() +  "base/role/validateRoleFlag",
        			type: "post",
        			data:{
        				newRoleFlag:function(){
        					return $("#roleFlag").val();
    					}
        			}
        		}
        	}
        },
        messages:{
        	roleName:"请输入角色名称",
    		roleFlag: {
        		required:"请输入角色标识",
        		remote: "已存在此角色标识，请重输"
        	}
        },
        errorPlacement: function(eror,element){
        	/*var toolTip = toolTips[element.attr("id")];
            if(!toolTip){
                toolTip =   element.jBox('Tooltip', {
                    id:element.attr("id") + "-error",
                    position: {
                        x: 'right',
                        y: 'center'
                    },
                    outside: 'x'
                });
                element.trigger("mouseenter");
                toolTips[element.attr("id")] = toolTip;
            } else{
                toolTip.attach();
                element.trigger("mouseenter");
            }
            toolTip.setContent(eror.text());
            element.addClass("error-border");*/	
        	 var toolTip = createTooltip(toolTips,element.attr("id"));
	            toolTip.setContent(eror.text());
	            toolTip.close();
	            element.addClass("error-border");
        },
        success:function(label){
            var elementId = label.attr("id").substring(0,label.attr("id").length - 6);
            var toolTip = toolTips[elementId];
            $("#" + elementId).removeClass("error-border");
            toolTip.close();
            toolTip.detach();
        },
        submitHandler:function(form){
        	var roleName = $("#add_roleName").val();
        	var roleFlag = $("#roleFlag").val();
        	//获取角色的基本权限所有节点
        	var baseAuthorityIds = "";
        	$("span[name=baseAuthority]").each(function(){
        		if($(this).hasClass("selected")){
        			baseAuthorityIds+=this.id+",";
        		}
        		
        	});
        	if(baseAuthorityIds.length>0){
        		baseAuthorityIds=baseAuthorityIds.substring(0,baseAuthorityIds.length-1);
        	}

        	//角色的菜单查看权限
        	var menuLookAuthorityIds = "";
        	//角色的菜单操作权限
        	var menuOperateAuthorityIds = "";
            	$("span[name=menuAuthority]").each(function(){
            		if($(this).hasClass("selected")){
            			if($(this).attr("pid")==-1){
            				menuLookAuthorityIds+=this.id+",";
            			}else{
            				if(this.id!="allcheck"&&menuOperateAuthorityIds.indexOf(this.id)==-1){
            					menuOperateAuthorityIds+=this.id+",";
            				}
            				
            			}
            		}
            	});
            	if(menuLookAuthorityIds.length>0){
            		menuLookAuthorityIds=menuLookAuthorityIds.substring(0,menuLookAuthorityIds.length-1);
            	}
            	if(menuOperateAuthorityIds.length>0){
            		menuOperateAuthorityIds=menuOperateAuthorityIds.substring(0,menuOperateAuthorityIds.length-1);
            	}
           loadDiv.showLoading();	
           post(getPath() + "base/role/add",{roleName:roleName,roleFlag:roleFlag,
        	   baseAuthorityIds:baseAuthorityIds,menuLookAuthorityIds:menuLookAuthorityIds,
        	   menuOperateAuthorityIds:menuOperateAuthorityIds},
        	   function(resultObject){
                   var errors = resultObject.errors;
                   //判断后台是否有返回错误消息
                   if(errors && errors.length > 0){
                   	loadDiv.hideLoading();
                       for(var i=0; i < errors.length; i++){
                           var error = errors[i];
                           var toolTip = createTooltip(toolTips,error.field);
                           toolTip.setContent(error.defaultMessage);
                           $("#" + error.field).addClass("error-border");
                       }
                   }else{
                   	loadDiv.hideLoading();
                       createWindow("添加成功",{url: getPath()+"base/role/list/1/"+pageSize}).dialog("open");
                   }
               },function(resultObject){
           		loadDiv.hideLoading();
           		createWindow(resultObject).dialog('open');
           	});
        }
    });

    //隐藏列表，显示添加
	$('#addDialog').show();
	$('#grid-list').hide();

	//取消
	$('#cancleBtn').click(function(){
		$('#addDialog').hide();
		$('#grid-list').show();
	});
}

function changeBaseAllCheck(id){
	if($("span[id="+id+"][name=baseAuthority]").hasClass('selected')){
		$("span[name=baseAuthority][id="+id+"]").removeClass('selected');
		$("span[name=baseAuthority][pid="+id+"]").removeClass('selected');
	}else{
		$("span[name=baseAuthority][id="+id+"]").addClass('selected');
		$("span[name=baseAuthority][pid="+id+"]").addClass('selected');
	}
}

function changeBaseChildCheck(pid,id){
	if($("span[id="+id+"][pid="+pid+"][name=baseAuthority]").hasClass('selected')){
		$("span[id="+id+"][pid="+pid+"][name=baseAuthority]").removeClass('selected');
		$("span[id="+pid+"][name=baseAuthority]").removeClass('selected');
	}else{
		$("span[id="+id+"][pid="+pid+"][name=baseAuthority]").addClass('selected');
		 var allLen = $("span[pid="+pid+"][name=baseAuthority]").length;
         var selectedLen = $("span[pid="+pid+"][class='checkbox selected'][name=baseAuthority]").length;
         if(allLen == selectedLen){
        	 $("span[id="+pid+"][name=baseAuthority]").addClass('selected');
         }
	}

}

function changeMenuAllCheck(pid){
	if($("span[id=allcheck][pid="+pid+"][name=menuAuthority]").hasClass('selected')){
		$("[pid="+pid+"][name=menuAuthority]").each(function(){
			id=this.id;
			if(id=="allcheck"){
				$("span[id=allcheck][pid="+pid+"][name=menuAuthority]").removeClass('selected');
			}else{
				if($("span[id="+id+"][pid="+pid+"][name=menuAuthority]").hasClass('selected')){
					changeMenuChildCheck(id);
				}
			}

		});
		
	}else{
		$("[pid="+pid+"][name=menuAuthority]").each(function(){
			id=this.id;
			if(id=="allcheck"){
				$("span[id=allcheck][pid="+pid+"][name=menuAuthority]").addClass('selected');
			}else{
				if(!$("span[id="+id+"][pid="+pid+"][name=menuAuthority]").hasClass('selected')){
					changeMenuChildCheck(id);
				}
			}

		});
		
	}
}

function changeMenuChildCheck(id){
	$("span[id="+id+"][name=menuAuthority]").each(function(){
		var pid=$(this).attr("pid");
		if($("span[id="+id+"][pid="+pid+"][name=menuAuthority]").hasClass('selected')){
			$("span[id="+id+"][pid="+pid+"][name=menuAuthority]").removeClass('selected');
			$("span[id=allcheck][pid="+pid+"][name=menuAuthority]").removeClass('selected');
		}else{
			$("span[id="+id+"][pid="+pid+"][name=menuAuthority]").addClass('selected');
			 var allLen = $("span[pid="+pid+"][name=menuAuthority][id!=allcheck]").length;
	         var selectedLen = $("span[pid="+pid+"][class='checkbox selected'][name=menuAuthority][id!=allcheck]").length;
	         if(allLen == selectedLen){
	        	 $("span[id=allcheck][pid="+pid+"][name=menuAuthority]").addClass('selected');
	         }
		}
	});
}
function changeMenuCheck(id){
	if($("span[id="+id+"][name=menuAuthority]").hasClass('selected')){
		$("div[id="+id+"]").find('span').removeClass('selected');
	}else{
		$("div[id="+id+"]").find('span').addClass('selected');
	}

}


